package com.wzh.sending;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.PopupWindow;
import android.widget.Toast;


import com.wzh.sending.info.PhoneInfo;
import com.wzh.sending.info.UsersInfo;
import com.wzh.sending.service.MyService;
import com.wzh.sending.utils.FileUtil;
import com.wzh.sending.utils.MyUtils;
import com.wzh.sending.view.RoundImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.bmob.v3.update.BmobUpdateAgent;


public class MainActivity extends CheckPermissionsActivity implements View.OnClickListener {
    Intent intent;
    Button btnStart, btnStop;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.my_switch)
    CheckBox mySwitch;
    SharedPreferences preferences;
    Handler handler;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            finish();
        }
    };
    @Bind(R.id.iv_headportrait)
    RoundImageView ivHeadportrait;
    private PopupWindow popuWindow;//显示获取图片方式的popuwindows
    private View contentView;//底部的弹窗布局
    private View parent;

    private Button btn_camera;//相机
    private Button btn_photo;//相册
    private Button btn_cancel;//相册
    private String imgName;
    private static final int REQUE_CODE_CAMERA = 1;
    private static final int REQUE_CODE_PHOTO = 2;
    private static final int REQUE_CODE_CROP = 3;
    private File cameraFile; // 保存拍照后的图片文件
    private Bitmap cropBitmap; // 保存裁剪后的图片
    private String dataimg;
    PhoneInfo phoneInfo;
    UsersInfo usersInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        usersInfo=new UsersInfo();
        phoneInfo = new PhoneInfo(getBaseContext());
        contentView = View.inflate(this, R.layout.layout_takephoto, null);
        btn_camera = (Button) contentView.findViewById(R.id.camara);
        btn_photo = (Button) contentView.findViewById(R.id.photo);
        btn_cancel = (Button) contentView.findViewById(R.id.cancel);
        preferences = getBaseContext().getSharedPreferences("loc", Context.MODE_PRIVATE);
        setNoBarTitle(toolbar, "个人定位");
        btnStart = (Button) findViewById(R.id.btn_start);
        btnStop = (Button) findViewById(R.id.btn_stop);
        intent = new Intent(this, MyService.class);
        handler = new Handler();
        if (preferences.contains("url")){
            if (!TextUtils.isEmpty(preferences.getString("url",null))){
                Bitmap bitmap = getLoacalBitmap(preferences.getString("url",null)); //从本地取图片
                ivHeadportrait.setImageBitmap(bitmap);
            }
        }


        if (preferences.contains("issend")) {
            mySwitch.setChecked(preferences.getBoolean("issend", false));
            if (preferences.getBoolean("issend", false)) {
                start();
            } else {
                stop();
                Intent intent2 = new Intent(this, FindUserActivity.class);
                startActivity(intent2);
                finish();
            }
        } else {
            start();
        }

        initEnent();
    }
    /**
     * 加载本地图片
     * http://bbs.3gstdy.com
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    private void initEnent() {
        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        ivHeadportrait.setOnClickListener(this);
        btn_camera.setOnClickListener(this);
        btn_photo.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                preferences.edit().putBoolean("issend", b).commit();
                if (b) {
                    start();
                } else {
                    stop();
                    Intent intent2 = new Intent(getBaseContext(), FindUserActivity.class);
                    startActivity(intent2);
                    finish();
                }
                Log.e("B", b + "");
            }
        });


    }

    public void start() {
        if (MyUtils.isNetworkAvailable(this)) {
            startService(intent);
            handler.postDelayed(runnable, 5000);
        } else {
            stop();
        }
    }

    public void stop() {
        stopService(intent);
        handler.removeCallbacks(runnable);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                start();
                break;
            case R.id.btn_stop:
                stop();
                break;
            case R.id.iv_headportrait:
                showPopuWindow();
                break;
            case R.id.cancel:
                dissmissPopuWindow();
                break;
            case R.id.photo:
             Intent   intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, REQUE_CODE_PHOTO);
                popuWindow.dismiss();
                break;
            case R.id.camara:
                Intent  intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File fileDir;
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    fileDir = new File(
                            Environment.getExternalStorageDirectory()
                                    + "/user_photos");
                    if (!fileDir.exists()) {
                        fileDir.mkdirs();
                    }
                } else {
                    Toast.makeText(this, "SD卡不在", Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
                imgName = System.currentTimeMillis() + ".png";
                cameraFile = new File(fileDir.getAbsoluteFile() + "/" + imgName);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(cameraFile));
                startActivityForResult(intent2, REQUE_CODE_CAMERA);
                popuWindow.dismiss();
                break;
        }
    }

    private void dissmissPopuWindow() {
        if (popuWindow != null && popuWindow.isShowing()) {
            popuWindow.dismiss();
            popuWindow = null;
        }
    }

    private void showPopuWindow() {
        if (null == popuWindow) {
            popuWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        popuWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.CENTER | Gravity.BOTTOM, 0, 0);
        popuWindow.setAnimationStyle(android.R.style.Animation_InputMethod);   // 设置窗口显示的动画效果
        popuWindow.setFocusable(false);                                        // 点击其他地方隐藏键盘 popupWindow
        popuWindow.update();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUE_CODE_CAMERA:
                    startPhotoZoom(Uri.fromFile(cameraFile));
                    break;
                case REQUE_CODE_PHOTO:
                    if (null != data) {
                        startPhotoZoom(data.getData());
                        cropBitmap = data.getParcelableExtra("data");
                    }
                    if (cropBitmap != null) {
                        String qimg = System.currentTimeMillis() + ".png";// 糗事图片
//                        Log.e("imgName","照片名字"+qimg);
                        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
                        cropBitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
                        byte[] bytes = bStream.toByteArray();
                        dataimg = Base64.encodeToString(bytes, Base64.DEFAULT);

//                        Log.e("saddimg",cropBitmap.toString());
                        ivHeadportrait.setImageBitmap(cropBitmap);
                    }
                    break;
                case REQUE_CODE_CROP:
                    setPicToView(data);
                    break;
                default:
                    break;
            }

        }
    }
    /**
     * 保存裁剪之后的图片数据
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            // 取得SDCard图片路径做显示
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(null, photo);
            final String urlpath = FileUtil.saveFile(getBaseContext(), "temphead.jpg", photo);
            ivHeadportrait.setImageDrawable(drawable);
            Log.e("uri",urlpath);
            final BmobFile bmobFile = new BmobFile(new File(urlpath));
            bmobFile.uploadblock( new UploadFileListener() {
                @Override
                public void done(BmobException e) {
                    if (e==null){
                        BmobQuery<UsersInfo> query = new BmobQuery<UsersInfo>();
                        query.addWhereEqualTo("imeiNo", phoneInfo.getImeiNo());
                        query.findObjects(new FindListener<UsersInfo>() {
                            @Override
                            public void done(List<UsersInfo> list, BmobException e) {
                                Log.e("list", list.size() + "");
                                if (e == null) {
                                    if (list.size() == 0) {
                                        if (usersInfo == null) {
                                            usersInfo = new UsersInfo();
                                        }
                                        usersInfo.setName("暂无姓名");
                                        usersInfo.setLineNo(phoneInfo.getNativePhoneNumber());
                                        usersInfo.setImeiNo(phoneInfo.getImeiNo());
                                        usersInfo.setHeardUrl(bmobFile.getFileUrl());
                                        usersInfo.setLat(0);
                                        usersInfo.setLot(0);
                                        usersInfo.setAddRess("暂无");
                                        usersInfo.save(new SaveListener<String>() {
                                            @Override
                                            public void done(String s, BmobException e) {
                                                if (e == null) {

                                                    Log.e("新用户：", s);
                                                } else {
                                                    Log.e("error：", e.getMessage());
                                                }
                                            }
                                        });

                                    } else if (list.size() == 1) {
                                       usersInfo.setHeardUrl(bmobFile.getFileUrl());
                                        usersInfo.update(list.get(0).getObjectId(), new UpdateListener() {
                                            @Override
                                            public void done(BmobException e) {
                                                if (e==null){
                                                    preferences.edit().putString("url",urlpath).commit();
                                                }
                                            }
                                        });


                                    }

                                }

                            }
                        });

                        Log.e("upurl","上传文件成功:" + bmobFile.getFileUrl());
                    }else {
                        Log.e("e",e.getMessage());

                    }
                }
            });

        }
    }
    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 裁剪图片方法实现
     */
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("output", Uri.fromFile(new File("/mnt/sdcard/temp")));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUE_CODE_CROP);
    }
}
